package com.situ.crm.resolver;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import com.situ.crm.common.exception.AuthorizationException;
import com.situ.crm.common.exception.BusinessException;
import com.situ.crm.vo.ResultDataVO;

@ControllerAdvice
public class WebExceptionResolver {

	@ExceptionHandler(BusinessException.class)
	public ResponseEntity<Object> exceptionHandler2(BusinessException e, HttpServletRequest request) {
		ResultDataVO vo = new ResultDataVO();
		// 创建此异常时指定了国际化文件中的key,返回给前台的错误提示从国际化配置文件中获取
		if (e.getKey() != null && e.getKey() != "") {
			RequestContext context = new RequestContext(request);
			String message = context.getMessage(e.getKey());
			if (message != null && message != "") {
				vo.setMsg(message);
			}
		}
		if (vo.getMsg() == null) {//如果没有返回错误消息，就把异常中的错误内容直接返回
			vo.setMsg(e.getMsg());
		}
		vo.setCode(1);
		return new ResponseEntity<>(vo, HttpStatus.INTERNAL_SERVER_ERROR);
	}

	@ExceptionHandler(AuthorizationException.class)
	public Object exceptionHandler3(HttpServletRequest request) {
		/**
		 * http 请求状态码 200 成功 302 转发 400 请求的地址对了，但是这个方法要求的参数没传对 401 没授权 404 找不到 500
		 * 系统内部错误
		 */
		if (isAjax(request)) {// 判断当前这是请求是不是ajax
			return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
		} else {
			ModelAndView mav = new ModelAndView("login");
			return mav;
		}
	}

	private boolean isAjax(HttpServletRequest request) {
		String requestWith = request.getHeader("X-Requested-With");
		return requestWith != null && "XMLHttpRequest".equals(requestWith);
	}

	@ExceptionHandler(Exception.class)
	public ResponseEntity<Object> exceptionHandler1(Exception e) {
		e.printStackTrace();
		ResultDataVO vo = new ResultDataVO();
		vo.setMsg("系统内部处理错误，请联系管理员");
		vo.setCode(1);
		return new ResponseEntity<>(vo, HttpStatus.INTERNAL_SERVER_ERROR);
	}

}
